<?php
include("./config/session-action.php");
include("./config/config.inc.php");
include("./config/QuickMySQL.php");
include("./config/function.inc.php");
include("./class/class.phpmailer.php");

/*发送邮件处理类*/
class CSendEMailAction extends JsonBase
{
	/* 获取远程的HTML数据 */
	function OnGetUrlData(){
		if( !isset($_POST['url']) ){
			$this->json["msg"] = "未指定要获取URL地址";	
			return;
		}
		$url = parse_url($_POST['url']);
		$error = "";
		if( !isset($url['host']) ){
			$this->json["msg"] = "未指定主机";	
			return;
		}
		$file = $url["scheme"] . "://" . $url['host'] . ":" . ( (!isset($url['port']))?"80":$url['port'] ) . "/" . ( (!isset($url['path']))?"":$url['path'] );
		$html = @file_get_contents($file);
		$codepage = "utf-8";
		$reg = "/\<meta\s*http-equiv\s*=\s*[\"\']Content-Type[\"\']\s*content\s*=\s*[\"\']text\/html;\s*charset\s*=\s*([^\"\']+)[\"\']\s*\/?>/i";
		// 转换编码
		if(preg_match($reg, $html, $cpa)){
			if(isset($cpa[1])){
				$codepage = strtolower($cpa[1]);
			}
			$html = preg_replace($reg, "<meta http-equiv=\"Content-Type\" content=\"text\/html; charset=utf-8\" />", $html);
		}
		// 输出
		if("utf-8" != $codepage)
			$html = @iconv($codepage, "utf-8", $html);
		$this->json["msg"] = $html;
		$this->json["success"] = true;
	}
	/*发送测试邮件*/
	function OnSendTestMail(){
		if(!isset($_POST['title']) || !isset($_POST['test']) || !isset($_POST['sendemail_preview'])){
			$this->json["msg"] = "参数错误";
			return;
		}
		
		global $sendmail_host, $sendmail_port, $sendmail_user, $sendmail_pwd;
		global $sendmail_from, $sendmail_from_name;
		
		$tos = explode(";", $_POST['test']);
		$mailto = "";
		//$mailreg = "/^[a-z]([a-z0-9]*[-_.]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[.][a-z]{2,3}([.][a-z]{2})?$/i";
		$mailreg = "/^([a-z0-9]*[-_.]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[.][a-z]{2,3}([.][a-z]{2})?$/i";
		
		$mail = new PHPMailer();
		$mail->CharSet = "UTF-8"; // 邮件编码
		$mail->Encoding = "base64";
		$mail->IsSMTP(); // 设定使用SMTP服务
		$mail->SMTPAuth = true;
		$mail->SMTPSecure = "ssh";
		$mail->Host = $sendmail_host; // 邮箱主机
		$mail->Port = $sendmail_port; // 端口号
		$mail->Username = $sendmail_user; // 用户名
		$mail->Password = $sendmail_pwd; // 密码
		$mail->SetFrom($sendmail_from, $sendmail_from_name); // 设置发件人
		$mail->Subject = $_POST['title']; // 标题
		//$mail->MsgHTML($_POST['sendemail_preview']);
		$mail->IsHTML(true);
		//$mail->Body = $_POST['sendemail_preview']; // 内容
		// 一定要注意替换内容
		$mail->Body=eregi_replace("[\](.)",'\\1',$_POST['sendemail_preview']);
		
		foreach($tos as $to){
			if(0 == preg_match($mailreg, $to))
				continue;
			// 发送邮件
			$mail->ClearAddresses();
			$mail->AddAddress($to);
			if( $mail->Send() ){
				$mailto .= ";{$to}";
			}
		}
		
		if( "" != $mailto ){
			$this->json["msg"] = $mailto;
			$this->json["success"] = true;
		} else {
			$this->json["msg"] = "发送邮件失败: " . $mail->ErrorInfo;
		}
	}
	/* 发送测试邮件 */
	function OnSendTest(){
		$emailid = (int)$_POST['email'];
		$subject = str_replace("'", "''", isset($_POST['title'])?$_POST['title']:"");
		// 获以发送内容
		$body = "";
		if( 0 == (int)$_POST['mtype'] ){
			$body = $this->http_get($_POST['url']);
			if( false == $body ){
				$this->json["msg"] = "获取远程数据失败";
				return;
			}
			$body = str_replace("'", "''", $body);
		} else {
			$body = str_replace("'", "''", isset($_POST['sendbody'])?$_POST['sendbody']:"");
		}
		$tos = explode(";", $_POST['test']);
		$mailreg = "/^([a-z0-9]*[-_.]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[.][a-z]{2,3}([.][a-z]{2})?$/i";
		/* 查询EMAIL数据 */
		$sql = "select addr, name, smtp, user, pwd, port from t_email_list where id={$emailid}";
		$mysql = new QuickMySQL();
		$res = $mysql->Query($sql);
		if( !($row = mysql_fetch_row($res)) ){
			$this->json["msg"] = "不正确的发送邮件地址";
			return;
		}
		$from = $row[0];
		$name = $row[1];
		$smtp = $row[2];
		$usr = $row[3];
		$pwd = $row[4];
		$port = (int)$row[5];
		mysql_free_result($res);
		
		$mail = new PHPMailer();
		$mail->CharSet = "UTF-8"; // 邮件编码
		$mail->Encoding = "base64";
		$mail->IsSMTP(); // 设定使用SMTP服务
		$mail->SMTPAuth = true;
		$mail->SMTPSecure = "ssh";
		$mail->Host = $smtp; // 邮箱主机
		$mail->Port = $port; // 端口号
		$mail->Username = $usr; // 用户名
		$mail->Password = $pwd; // 密码
		$mail->SetFrom($from, $name); // 设置发件人
		$mail->Subject = $_POST['title']; // 标题
		//$mail->MsgHTML($_POST['sendemail_preview']);
		$mail->IsHTML(true);
		//$mail->Body = $_POST['sendemail_preview']; // 内容
		// 一定要注意替换内容
		$mail->Body=eregi_replace("[\](.)",'\\1',$body);
		
		foreach($tos as $to){
			if(0 == preg_match($mailreg, $to))
				continue;
			// 发送邮件
			$mail->ClearAddresses();
			$mail->AddAddress($to);
			if( $mail->Send() ){
				$mailto .= ";{$to}";
			}
		}
		
		if( "" != $mailto ){
			$this->json["msg"] = $mailto;
			$this->json["success"] = true;
		} else {
			$this->json["msg"] = "发送邮件失败: " . $mail->ErrorInfo;
		}
	}
	/* 从网页获取数据 */
	function http_get($urlpath){
		$url = parse_url($urlpath);
		$error = "";
		if( !isset($url['host']) ){
			return false;
		}
		$file = $url["scheme"] . "://" . $url['host'] . ":" . ( (!isset($url['port']))?"80":$url['port'] ) . "/" . ( (!isset($url['path']))?"":$url['path'] );
		if( false == ($html = @file_get_contents($file)) )
			return false;
		$codepage = "utf-8";
		$reg = "/\<meta\s*http-equiv\s*=\s*[\"\']Content-Type[\"\']\s*content\s*=\s*[\"\']text\/html;\s*charset\s*=\s*([^\"\']+)[\"\']\s*\/?>/i";
		// 转换编码
		if(preg_match($reg, $html, $cpa)){
			if(isset($cpa[1])){
				$codepage = strtolower($cpa[1]);
			}
			$html = preg_replace($reg, "<meta http-equiv=\"Content-Type\" content=\"text\/html; charset=utf-8\" />", $html);
		}
		if("utf-8" != $codepage)
			$html = @iconv($codepage, "utf-8", $html);
		return $html;
	}
	/* 添加发送队列 */
	function OnAddSend(){
		$email = (int)$_POST['email'];
		$subject = str_replace("'", "''", isset($_POST['title'])?$_POST['title']:"");
		$stype = (int)$_POST['stype'];
		// 获以发送内容
		$body = "";
		if( 0 == (int)$_POST['mtype'] ){
			$body = $this->http_get($_POST['url']);
			if( false == $body ){
				$this->json["msg"] = "获取远程数据失败";
				return;
			}
			$body = str_replace("'", "''", $body);
		} else {
			$body = str_replace("'", "''", isset($_POST['sendbody'])?$_POST['sendbody']:"");
		}
		$sqluser = "";
		// 构造私有数据
		if( 0 == $stype ) {
			// 写邮件群发队列
			$group = "t_user_" . $_POST['group'];
			$sendnow = isset($_POST['sendnow'])?1:0;
			$flag = (int)$_POST['group3'];
			$sendint = (int)$_POST['sendint'];
			if( $sendint < 1 ) $sendint = 1;
			$sendint = $sendint * 10;
			$sendcount = (int)$_POST['sendcount'];
			if( $sendcount < 1 ) $sendcount = 1;
			$sql = "insert into t_sendemail_group(m_no,sm_to,sm_subject,sm_run,sm_flag,sm_interval,sm_max,sm_body)"
				. " values({$email}, '{$group}', '{$subject}', {$sendnow}"
				. " , {$flag}, {$sendint}, {$sendcount}, '{$body}')";
			$sqluser = "update {$group} set sem_n = sem_n & ~(1 << {$flag})";
		} else {
			// 写邮件到期队列
			$group = "t_user_" . $_POST['group2'];
			$sendnow = isset($_POST['sendnow_2'])?1:0;
			$lastdt = (int)$_POST['lastday'];
			if( $lastdt < 1 ) $lastdt = 1;
			$cycle = (int)$_POST['cycle'];
			if( $cycle < 1 ) $cycle = 1;
			$sql = "insert into t_sendemail_notify(m_no,sm_to,sm_subject,sm_run,sm_lastday,sm_cycle,sm_body)"
				. " values({$email}, '{$group}', '{$subject}', {$sendnow}, {$lastdt}, {$cycle}, '{$body}')";
		}
		// 发送SQL
		if( QuickMySQL::quickExecute($sql) ){
			if("" != $sqluser)
				QuickMySQL::quickExecute($sqluser);
			$this->json["success"] = true;
			$this->json["msg"] = "添加" . ( (0 == $stype)?"群发":"到期提醒" ) . "任务成功";
		} else {
			$this->json["msg"] = "添加失败，请稍后重试";
		}
	}
}

set_time_limit(0);
/*发送邮件操作*/
$cc = new CSendEMailAction();

?>